<script>
import {saveBookItem, updateBook} from "@/utils";

export default {
  name: "BookDetail.vue",
  data() {
    return {
      bookFormData: {
        id: undefined,
        bookName: '',
        author: '',
        number: undefined,
        press: '',
      }
    }
  },
  props: {
    bookItem: {
      type: Object,
    },
    isNewBook: {
      type: Boolean,
      require: true,
    }
  },
  mounted() {
    if (!this.isNewBook) {
      this.bookFormData.id = this.bookItem.id
      this.bookFormData.bookName = this.bookItem.bookName
      this.bookFormData.author = this.bookItem.author
      this.bookFormData.number = this.bookItem.number
      this.bookFormData.press = this.bookItem.press
    }
  },
  methods: {
    addBook() {
      console.log("新增")
      // 校验数据
      // 保存数据
      saveBookItem(this.bookFormData)
      // 跳转到首页
      this.$router.push({name: 'home'})
    },
    updateBook() {
      console.log("编辑")
      updateBook(this.bookFormData)
      this.$router.push({name: 'home'})
    },
    submitBook() {
      if (confirm("是否确认提交")) {
        console.log(this.bookFormData)
        if (this.isNewBook) {
          this.addBook()
        } else {
          this.updateBook()
        }
      } else {
        console.log("取消了提交")
      }
    }
  }
}
</script>

<template>
  <div>
    <form class="container">
      <div v-if="!isNewBook" class="form-group">
        <span>ID:</span>
        <input v-model="bookFormData.id" placeholder="请输入ID" readonly/>
      </div>
      <div class="form-group">
        <span>书名:</span>
        <input v-model="bookFormData.bookName" placeholder="请输入书名"/>
      </div>
      <div class="form-group">
        <span>作者:</span>
        <input v-model="bookFormData.author" placeholder="请输入作者"/>
      </div>
      <div class="form-group">
        <span>编号:</span>
        <input v-model="bookFormData.number" placeholder="请输入编号"/>
      </div>
      <div class="form-group">
        <span>出版社:</span>
        <input v-model="bookFormData.press" placeholder="请输入出版社"/>
      </div>
    </form>
    <div>
      <button style="margin-right: 5px" @click="submitBook">提交</button>
      <router-link to="/" tag="button">返回</router-link>
    </div>
  </div>
</template>

<style scoped>
.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.form-group span {
  display: inline-block;
  width: 60px; /* 固定宽度 */
  text-align: right;
  margin-right: 10px;
}

.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

</style>